package com.mall.order.biz.handler;/**
 * Created by ciggar on 2019/8/1.
 */

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.OrderShipping;
import com.mall.order.dal.persistence.OrderShippingMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * ciggar
 * create-date: 2019/8/1-下午5:06
 * <p>
 * 处理物流信息（商品寄送的地址）
 */
@Slf4j
@Component
public class LogisticalHandler extends AbstractTransHandler {

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        Date date = new Date();

        OrderShipping orderShipping = new OrderShipping();
        orderShipping.setCreated(date);
        orderShipping.setOrderId(createOrderContext.getOrderId());
        // streetName传进来是 比如：天津市-市辖区-南开区-232
        // 要进行字符串处理，根据-分割 state-city-district-address
        String streetName = createOrderContext.getStreetName();
        String[] split = streetName.split("-");
        // 传进来如果不是三个-分割，就报地址信息错误异常
        if (split.length != 4) {
            throw new BizException(OrderRetCode.ADDRESS_ERROR.getCode(), OrderRetCode.ADDRESS_ERROR.getMessage());
        }
        String state = split[0];
        String city = split[1];
        String district = split[2];
        String address = split[3];

        orderShipping.setReceiverAddress(address);
        orderShipping.setReceiverCity(city);
        orderShipping.setReceiverDistrict(district);
        // 前端只给了一个电话
//        orderShipping.setReceiverMobile();
        orderShipping.setReceiverName(createOrderContext.getUserName());
        orderShipping.setReceiverPhone(createOrderContext.getTel());
        orderShipping.setReceiverState(state);
        // 暂时不知道
//        orderShipping.setReceiverZip();
        orderShipping.setUpdated(date);

        try {
            int insert = orderShippingMapper.insert(orderShipping);
            if (insert != 1) {
                throw new Exception();
            }
        } catch (Exception e) {
            log.error(OrderRetCode.SHIPPING_DB_SAVED_FAILED.getMessage());
            throw new BizException(OrderRetCode.SHIPPING_DB_SAVED_FAILED.getCode(), OrderRetCode.SHIPPING_DB_SAVED_FAILED.getMessage());
        }

        return true;
    }
}
